package com.itheima.common;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.UUID;

@Slf4j
@RestController
@RequestMapping("/common")
public class CommonController {
    @Value("${common.path}")
    private String path;

    /**
     * 上传文件
     * @param file
     * @return
     */
    @PostMapping("/upload")
    public R<String> upload(MultipartFile file){
        //原始文件名
        String originalFilename = file.getOriginalFilename();//aaa.jpg

        String orig = originalFilename.substring(originalFilename.lastIndexOf(".")) ;
        log.info(originalFilename);

        //使用UUID重新生成文件名，防止文件名重复
        String filename = UUID.randomUUID().toString()+orig;

        File dir = new File(path);
        //判断文件夹是否存在，不存在就创建
        if (!dir.exists()){
            dir.mkdirs();
        }

        try {
            //将临时文件转存到指定位置
            file.transferTo(new File(path+filename));
        } catch (IOException e) {
            e.printStackTrace();
        }
        return R.success(filename);
    }

    /**
     * 下载文件
     * @param name
     * @param resp
     * @return
     */
    @GetMapping("/download")
    public void download(String name , HttpServletResponse resp){


        try {
            //输入流，通过输入流读取文件内容
            FileInputStream fileInputStream = new FileInputStream(new File(path + name));
            //输出流，通过输出流将文件写回浏览器
            ServletOutputStream outputStream = resp.getOutputStream();
            byte [] bytes = new byte[1024];
            int len;
            while((len=fileInputStream.read(bytes))!=-1){
                outputStream.write(bytes,0,len);
            }
            fileInputStream.close();
            outputStream.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}
